package com.jinyi.wwdeng.ui.main.act

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.view.View
import com.jinyi.base.utils.ForegroundBackgroundHelper
import com.jinyi.base.utils.ForegroundBackgroundObserver
import com.jinyi.base.utils.log.HHLog
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActMainBinding
import com.jinyi.wwdeng.pro.ProMvpAct
import com.jinyi.wwdeng.ui.main.contract.MainContract
import com.jinyi.wwdeng.ui.main.fragment.CreditApplyFailedFragment
import com.jinyi.wwdeng.ui.main.fragment.CreditAuditFragment
import com.jinyi.wwdeng.ui.main.fragment.CreditAuditFrenchFragment
import com.jinyi.wwdeng.ui.main.fragment.CreditLimitFragment
import com.jinyi.wwdeng.ui.main.fragment.CreditRepaymentFragment
import com.jinyi.wwdeng.ui.main.impl.MainPresenterImpl
import org.json.JSONObject

class MainAct : ProMvpAct<MainContract.View, MainPresenterImpl>(), MainContract.View {

    lateinit var binding: ActMainBinding

    //广播接收器
    private var mRecevier: ProcessUpdateRecevier? = null

    //贷款额度
    var limitFragment: CreditLimitFragment? = null

    //贷款还款
    var repaymentFragment: CreditRepaymentFragment? = null

    //贷款审核
    var auditFragment: CreditAuditFragment? = null

    //贷款审核（法语）
    var auditFrenchFragment: CreditAuditFrenchFragment? = null

    //贷款申请失败
    var applyFailedFragment: CreditApplyFailedFragment? = null

    override fun getRootView(): View {
        binding = ActMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): MainPresenterImpl {
        return MainPresenterImpl()
    }

    override fun initView() {
        setBackExit(true)
        setExitTips(getString(R.string.exit_tips))
        initPresenter()
        registerUpdateRecevier()
        ForegroundBackgroundHelper.addObserve(onForegroundBackgroundObserver)
    }

    override fun initListener() {
    }

    override fun initData() {
        loadProcessAction()
    }

    /**
     * 获取用户流程状态
     */
    private fun loadProcessAction() {
        showLoading("")
        presenter.loadProcessRequest()
    }

    /**
     * 用户流程状态更新成功
     */
    override fun updateProcessSuccess() {
        //发送广播通知接收者，用户流程状态已更新
        val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATED)
        sendBroadcast(intent)
    }

    /**
     * 显示贷款额度页面
     */
    override fun showCreditLimitPage(isComplete: Boolean) {
        hideAllPage()
        if (limitFragment == null) {
            limitFragment = CreditLimitFragment(isComplete)
        }
        if (limitFragment!!.isAdded) {
            showContainerFragement(limitFragment)
            limitFragment!!.isComplete = isComplete
            limitFragment!!.showCompleteView()
        } else {
            addContainerFragement(R.id.containerLayout, limitFragment)
        }
    }

    /**
     * 显示待还款页面
     */
    override fun showCreditRepaymentPage() {
        hideAllPage()
        if (repaymentFragment == null) {
            repaymentFragment = CreditRepaymentFragment()
        }
        if (repaymentFragment!!.isAdded) {
            showContainerFragement(repaymentFragment)
        } else {
            addContainerFragement(R.id.containerLayout, repaymentFragment)
        }
    }

    /**
     * 显示放款中
     */
    override fun showCreditAuditPage(data: JSONObject) {
        hideAllPage()
        //法语地区
        if (AppConfigs.isFrench()) {
            if (auditFrenchFragment == null) {
                auditFrenchFragment = CreditAuditFrenchFragment(data)
            }
            if (auditFrenchFragment!!.isAdded) {
                showContainerFragement(auditFrenchFragment)
            } else {
                addContainerFragement(R.id.containerLayout, auditFrenchFragment)
            }
        } else {
            if (auditFragment == null) {
                auditFragment = CreditAuditFragment(data)
            }
            if (auditFragment!!.isAdded) {
                showContainerFragement(auditFragment)
            } else {
                addContainerFragement(R.id.containerLayout, auditFragment)
            }
        }
    }

    /**
     * 显示贷款申请被拒绝页面
     */
    override fun showCreditApplyFailedPage(data: JSONObject) {
        hideAllPage()
        if (applyFailedFragment == null) {
            applyFailedFragment = CreditApplyFailedFragment(data)
        }
        if (applyFailedFragment!!.isAdded) {
            showContainerFragement(applyFailedFragment)
        } else {
            addContainerFragement(R.id.containerLayout, applyFailedFragment)
        }
    }

    /**
     * 隐藏所有的页面
     */
    private fun hideAllPage() {
        if (limitFragment != null) {
            hideContainerFragement(limitFragment)
        }
        if (repaymentFragment != null) {
            hideContainerFragement(repaymentFragment)
        }
        if (auditFragment != null) {
            hideContainerFragement(auditFragment)
        }
        if (auditFrenchFragment != null) {
            hideContainerFragement(auditFrenchFragment)
        }
        if (applyFailedFragment != null) {
            hideContainerFragement(applyFailedFragment)
        }
    }

    /**
     * 注册更新用户流程状态广播
     */
    private fun registerUpdateRecevier() {
        mRecevier = ProcessUpdateRecevier(this)
        val intentFilter = IntentFilter()
        intentFilter.addAction(AppConfigs.Action.ACTION_PROCESS_UPDATE)//更新流程状态
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(mRecevier, intentFilter, Context.RECEIVER_EXPORTED)
        } else {
            registerReceiver(mRecevier, intentFilter)
        }
    }

    class ProcessUpdateRecevier(act: MainAct) : BroadcastReceiver() {
        var act = act
        override fun onReceive(context: Context, intent: Intent) {
            act.onRecevierEvent(intent)
        }
    }

    /**
     * 处理广播接收事件处理
     */
    private fun onRecevierEvent(intent: Intent) {
        //根据需求添加自己需要关闭页面的action
        when (intent.action) {
            AppConfigs.Action.ACTION_PROCESS_UPDATE -> {//更新流程状态
                HHLog.e(">>>>>>>>>>>>收到刷新总流程通知")
                presenter.loadProcessRequest()
            }
        }
    }

    /**
     * 前后台切换监听
     */
    private val onForegroundBackgroundObserver = object : ForegroundBackgroundObserver {
        override fun foregroundBackgroundNotify(isForeground: Boolean) {
            HHLog.e("Main是否进入后台了>>>>>>>>>$isForeground")
            //从桌面进入前台，需要刷新总流程
            if (isForeground) {
                presenter.loadProcessRequest()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this.mRecevier != null) {
            unregisterReceiver(this.mRecevier)
        }
        ForegroundBackgroundHelper.removeObserver(onForegroundBackgroundObserver)
    }
}
